import 'package:flutter_admin/api/odoo/mps_transit_odoo_api.dart';
import 'package:flutter_admin/models/odoo/mps_transit.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/odoo/mps_transit/mps_transit_dialog.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class MpsTransitList extends StatefulWidget {
  MpsTransitList({Key? key}) : super(key: key);
  @override
  _MpsTransitListState createState() => _MpsTransitListState();
}

class _MpsTransitListState extends State<MpsTransitList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  MpsTransit mpsTransit = MpsTransit();
  DateFormat format = DateFormat('yyyy-MM-dd');
  List<MpsTransit> selectedList = [];
  List<SelectOptionVO> alreadyDoneList = [];

  @override
  void initState() {
    super.initState();
    mpsTransit.alreadyDone = 'false';
    mpsTransit.createDateStart = Utils.getDate();
    mpsTransit.createDateEnd = Utils.getDate();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    alreadyDoneList = [
      SelectOptionVO(value: '', label: ""),
      SelectOptionVO(value: 'true', label: "是"),
      SelectOptionVO(value: 'false', label: "否"),
    ];
    _query();
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 180,
            label: '开始时间',
            value: mpsTransit.createDateStart,
            lastDate: isNotBlank(mpsTransit.createDateEnd)
                ? format.parse(mpsTransit.createDateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              mpsTransit.createDateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              mpsTransit.createDateStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '结束时间',
            value: mpsTransit.createDateEnd,
            firstDate: isNotBlank(mpsTransit.createDateStart)
                ? format.parse(mpsTransit.createDateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              mpsTransit.createDateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              mpsTransit.createDateEnd = v;
            },
          ),
          CryInput(
            width: 160,
            label: '产品名称',
            value: mpsTransit.productName,
            onSaved: (v) {
              mpsTransit.productName = v;
            },
          ),
          CryInput(
            width: 160,
            label: '产品编码',
            value: mpsTransit.defaultCode,
            onSaved: (v) {
              mpsTransit.defaultCode = v;
            },
          ),
          CrySelect(
            width: 200,
            label: '是否已完成',
            dataList: alreadyDoneList,
            value: mpsTransit.alreadyDone,
            onSaved: (v) {
              mpsTransit.alreadyDone = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('产品编码')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('单位')),
        DataColumn(label: Text('日期')),
        DataColumn(label: Text('采购数')),
        DataColumn(label: Text('入库数')),
        DataColumn(label: Text('是否已完成')),
      ],
      getCells: (m) {
        MpsTransit mpsTransit = MpsTransit.fromMap(m);
        return [
          DataCell(Text(mpsTransit.productName ?? '--')),
          DataCell(Text(mpsTransit.defaultCode ?? '--')),
          DataCell(Text(mpsTransit.description ?? '--')),
          DataCell(Text(mpsTransit.uom ?? '--')),
          DataCell(Text(Utils.timeUTC(mpsTransit.createDate))),
          DataCell(Text(mpsTransit.qtyTransit ?? '--')),
          DataCell(Text(mpsTransit.qtyReceive ?? '--')),
          DataCell(Text(mpsTransit.alreadyDone == 'true' ? '是' : '否')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
          label: "导出",
          onPressed: () => _generateExcel(),
          iconData: Icons.import_export_outlined,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    mpsTransit = MpsTransit();
    formKey.currentState!.reset();
    mpsTransit.createDateStart = Utils.getDate();
    mpsTransit.createDateEnd = Utils.getDate();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await MpsTransitApi.page(
        data: {"page": page, "domainList": mpsTransit.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  Future<dynamic> findAll() async {
    formKey.currentState?.save();
    List<MpsTransit> resultList = [];
    ResponseBodyApi responseBodyApi = await MpsTransitApi.findAll(data: {
      "domainList": mpsTransit.toDomainList(),
    });
    if (responseBodyApi.success!) {
      resultList = responseBodyApi.data
              .map<MpsTransit>((e) => MpsTransit.fromMap(e))
              .toList() ??
          [];
    }
    return resultList;
  }

  _generateExcel() async {
    List<MpsTransit> selectedList = await findAll();
    if (selectedList == null) {
      return;
    }
    List<Map> map = [
      {
        'name': 'productName',
        'label': '客户名称',
        'columnWidth': 40.0,
      },
      {
        'name': 'defaultCode',
        'label': '产品编码',
        'columnWidth': 10.0,
      },
      {
        'name': 'description',
        'label': '规格型号',
        'columnWidth': 12.0,
      },
      {
        'name': 'uom',
        'label': '单位',
        'columnWidth': 8.0,
      },
      {
        'name': 'createDate',
        'label': '日期',
        'columnWidth': 22.0,
      },
      {
        'name': 'qtyTransit',
        'label': '采购数',
        'columnWidth': 10.0,
      },
      {
        'name': 'qtyReceive',
        'label': '入库数',
        'columnWidth': 10.0,
      },
      {
        'name': 'alreadyDone',
        'label': '是否已完成',
        'columnWidth': 15.0,
      },
    ];
    Utils.generateExcel(fileName: "物料在途", configure: map, data: selectedList);
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: MpsTransitDialog(),
      ),
    ).then((v) {
      if (v != null) {
        mpsTransit = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<MpsTransit>((e) => MpsTransit.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.dmsFile) {
          _generateExcel();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          child: ListTile(
            leading: const Icon(Icons.import_export_outlined),
            title: Text('导出'),
          ),
        ),
      ],
    );
  }
}
